package xxy.com.yangproject.database.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import androidx.paging.ItemKeyedDataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PageKeyedDataSource;
import androidx.paging.PagedList;
import androidx.room.paging.LimitOffsetDataSource;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import xxy.com.yangproject.database.Dao.CheeseDao;
import xxy.com.yangproject.database.Entity.Cheese;
import xxy.com.yangproject.database.db.CheeseDb;

public class CheeseViewModel extends AndroidViewModel {

    private static CheeseDao cheeseDao;
    public final LiveData<PagedList<Cheese>> livePagedList;


    /**
     * 存数据的结构，有数据改动可以通过回调通知接收方进行相应操作,数据库进行更改
     * @param application
     */
    public CheeseViewModel(@NonNull Application application) {
        super(application);
        cheeseDao = CheeseDb.getDatabase(application).cheeseDao();
        livePagedList = new LivePagedListBuilder<PagedList<Cheese>, Cheese>(new DataSourceFactory(),
                new PagedList.Config.Builder()
                        .setPageSize(30)
                        .setEnablePlaceholders(true)
                        .build())
                .build();
        //Dao db entity
    }


    public static class DataSourceFactory extends DataSource.Factory<PagedList<Cheese>, Cheese>{
        //和pageing对应的SequentialDataSource
        SequentialDataSource sequentialDataSource = new SequentialDataSource();

        @NonNull
        @Override
        public DataSource<PagedList<Cheese>, Cheese> create() {
            return sequentialDataSource;
        }
    }

    public static class SequentialDataSource extends PageKeyedDataSource {
        public SequentialDataSource() {

        }

//        public javax.sql.DataSource getAllCheesesByName(){
//            return cheeseDao.allCheesesByName();
//        }

        @Override
        public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) {

        }

        @Override
        public void loadBefore(@NonNull LoadParams params, @NonNull LoadCallback callback) {

        }

        @Override
        public void loadAfter(@NonNull LoadParams params, @NonNull LoadCallback callback) {

        }
    }

    //插入
    public void insert(String text){
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                cheeseDao.insert(new Cheese(text));
            }
        });
    }

    //删除
    public void delete(Cheese cheese){
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                cheeseDao.delete(cheese);
            }
        });
    }
}
